package com.gao.netclient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;

public class NetClient {

    public Response sendRequest(Request request) {
        Response response = new Response();
        String resData = "";
        String msg = "";
        String reqData =  request.getData();
        String ip = request.getIp();
        int port = request.getPort();
        try {
            if (reqData != null && reqData.length() > 0) {
                Socket socket = new Socket(ip, port);
                InputStream in = socket.getInputStream();
                OutputStream out = socket.getOutputStream();
                int headerLen = request.getHeaderLen();
                reqData = String.format("%0" + headerLen + "d", reqData.getBytes(request.getCharset()).length) + reqData;
                out.write(reqData.getBytes(request.getCharset()));
                out.flush();
                long startT = System.currentTimeMillis();
                ByteBuffer buffer = ByteBuffer.allocate(1024000);
                for (int i = 0; i < request.getTimeout() && in.available() <= 0; ++i) {
                    Thread.sleep(1000);
                }
                long endT = System.currentTimeMillis();

                while (true) {
                    int len = in.available();
                    if (len <= 0) {
                        Thread.sleep(500);
                        if (in.available() <= 0) {
                            break;
                        }
                    }
                    byte[] data = new byte[len];
                    in.read(data, 0, len);
                    buffer.put(data);
                    Thread.sleep(10);
                }
                socket.close();
                if (buffer.position() == 0) {
                    msg = "请求超时(" + request.getTimeout() + "秒)";
                } else {
                    resData = new String(buffer.array(), 0, buffer.position(), request.getCharset());
                }
                msg = String.format("请求成功, 用时 %d ms" + "，返回内容长度 %d 字节", endT-startT, resData.getBytes().length);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg = "ip=" + ip + ", port=" + port + "连接异常！";
        }
        response.setMsg(msg);
        response.setResData(resData);
        return response;
    }
}
